package com.atguigu.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.*;

public class BIOServer {
    public static void main(String[] args) {
        //1.创建一个线程池
        //2.如果有客户端连接，就创建一个线程与之通信
        ExecutorService executorService=new ThreadPoolExecutor(5,5,3000, TimeUnit.MILLISECONDS,new LinkedBlockingDeque<>(100), Executors.defaultThreadFactory(),new ThreadPoolExecutor.DiscardPolicy());
        //创建serverSocket 监听6666端口
        ServerSocket serverSocket=null;
        try {
            serverSocket = new ServerSocket(6666);
            System.out.println("服务器启动了");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        while(true){
            //监听等待客户端连接
            try {
                Socket socket = serverSocket.accept();  //等待连接  会阻塞
                System.out.println("连接到一个客户端");
                executorService.execute(()->{
                    //和客户端通讯
                    handle(socket);
                });
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //编写一个handler方法和客户端通讯
    public static void handle(Socket socket){
        try{
            System.out.println("线程信息 id="+Thread.currentThread().getId()+" name="+Thread.currentThread().getName());
            byte[] bytes = new byte[1024];
            //socket 输入流
            InputStream inputStream = socket.getInputStream();
            //循环读取客户端发送的数据
            while(true){
                System.out.println("线程信息 id="+Thread.currentThread().getId()+" name="+Thread.currentThread().getName());
                int read = inputStream.read(bytes);  //等待数据  会阻塞
                if(read!=-1){
                    //输出客户端发送的数据
                    System.out.println(new String(bytes,0,read));
                }else{
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
